﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using CarLeasing.Forms;
using CarLeasing.Models;

namespace CarLeasing
{
    static class Program
    {
        static Data.LocalStore Store = null;

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Store = new Data.LocalStore(Config.DataFolder);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            CreateLoginForm().Show();

            Application.Run();
        }

        static LoginForm CreateLoginForm()
        {
            var login = new LoginForm();

            login.FormClosing += Exit;
            login.OnSwapToRegister += () =>
             {
                 using (var register = CreateRegisterForm())
                     register.ShowDialog();
             };

            login.OnLogin += (name, password) =>
              {
                  var user = Store.Of<User>().FirstOrDefault(x => x.Name == name && x.Password == password);
                  if (user == null)
                  {
                      MessageBox.Show("User name or password is wrong");
                      return;
                  }

                  login.FormClosing -= Exit;
                  login.Close();

                  CreateAllCarForm(user).Show();
            };

            return login;
        }

        static RegisterForm CreateRegisterForm()
        {
            var register = new RegisterForm();

            register.SwapToLogin += ()=>register.Close();
            register.Registered += (name, password) =>
              {
                  if (Store.Of<User>().Any(x => x.Name == name))
                  {
                      MessageBox.Show("User name is already used");
                      return;
                  }

                  Store.Of<User>().Add(new User(Guid.NewGuid(), name, password));
                  Store.Of<User>().Save();
                  MessageBox.Show("Registered");
                  register.Close();
              };

            return register;
        }

        static AllCarForm CreateAllCarForm(User user)
        {
            var allCars = new AllCarForm(user, Store);
            allCars.FormClosing += Exit;
            return allCars;
        }

        static void Exit(object sender, FormClosingEventArgs e) => Application.Exit();
    }
}
